﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QFileDialog>
#include <QColorDialog>
#include <QDebug>
#define consoleLog qDebug()
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

#define maxNum 1000000
static QString formatSN(quint64 num)
{
    QString temp = QString::number(num);
    int maxLength = QString::number(maxNum).length()-1;
    if(temp.length() < maxLength)
    {
        for(int index = temp.length(); index < maxLength; index++)
        {
            temp = "0" + temp;
        }
    }
    return temp;
}

//批量生产序列号
QStringList MainWindow::batchGenSN(quint64 startNum, quint64 quantity)
{
    QStringList result;
    if(startNum > maxNum)
    {
        QMessageBox::warning(0, "提示", QString("起始值不得超出%1").arg(maxNum-1));
        return result;
    }
    quint64 endNum = startNum + quantity;
    if(endNum > maxNum)
    {
         QMessageBox::StandardButton ret = QMessageBox::warning(0, "提示", QString("终止值已超出%1，最多为您生成%2，是否继续？").arg(maxNum-1).arg(maxNum-1), QMessageBox::Yes|QMessageBox::No);
         if(ret == QMessageBox::No)
         {
             return result;
         }
         endNum = maxNum;
    }
    for (quint64 index = startNum; index < endNum; index++)
    {
        result << formatSN(index);
    }
    return result;
}

void MainWindow::updateProgress()
{
    progressValue++;
    ui->progressBar->setValue(progressValue);
}

void MainWindow::on_btn_batchGenerate_clicked()
{
    progressValue = 0;
    QColor qrcolor = ui->frame_qrcolor->palette().background().color();
    QColor bgcolor = ui->frame_bgcolor->palette().background().color();

    quint64 startNum = ui->spin_startNum->value();
    quint64 quantity = ui->spin_quantityGen->value();
    ui->progressBar->setRange(0, quantity);
    QStringList batchSN = batchGenSN(startNum, quantity);

    QString savePath = ui->line_batchPath->text();
    QString imgFormat = ui->comBox_imgFormat->currentIndex()==1?".png":".jpg";
    QString fixedStr = ui->line_fixedString->text();
    for(auto temp:batchSN)
    {
        QString fullName = savePath + "/" + temp + imgFormat;
        QRgenerator* generator = new QRgenerator(nullptr, fixedStr + temp, fullName, QRect(0,0,ui->spin_width->value(),ui->spin_height->value()), qrcolor, bgcolor);
        connect(generator, &QRgenerator::finishGen, this, &MainWindow::updateProgress);
        QThreadPool::globalInstance()->start(generator);
    }
}

void MainWindow::on_btn_generate_clicked()
{
    QColor qrcolor = ui->frame_qrcolor->palette().background().color();

    QColor bgcolor = ui->frame_bgcolor->palette().background().color();

    QString content = ui->line_qrContent->text();
    int labelRsize = ui->label_encode->geometry().width()>=ui->label_encode->geometry().height()?ui->label_encode->geometry().height():ui->label_encode->geometry().width();
    QRgenerator generator(this, content, "", QRect(0,0,ui->spin_width->value(),ui->spin_height->value()), qrcolor, bgcolor);
    QPixmap pixmap = generator.GenerateQPixmap();
    ui->label_encode->setPixmap(pixmap.scaled(labelRsize,labelRsize,Qt::IgnoreAspectRatio,Qt::SmoothTransformation));
}

void MainWindow::on_btn_saveFile_clicked()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"),
                                                    QApplication::applicationDirPath(),
                                                    tr("Images (*.png *.jpg)"));
    if(fileName.isEmpty())
        return;
    QString format;
    if(fileName.endsWith("png"))
        format = "PNG";
    else if(fileName.endsWith("jpg"))
        format = "JPEG";
    const QPixmap *current_img = ui->label_encode->pixmap();
    QPixmap pixmap = current_img->scaled(ui->spin_width->value(),ui->spin_height->value(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
    pixmap.save(fileName, format.toLocal8Bit().data());
}

void MainWindow::on_btn_selectFile_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),
                                                    QApplication::applicationDirPath(),
                                                    tr("Images (*.png *.jpg)"));
    if(fileName.isEmpty())
        return;
    ui->line_filePath->setText(fileName);
    QPixmap pixmap(fileName);
    int QRsize = ui->label_decode->geometry().width()>=ui->label_decode->geometry().height()?ui->label_decode->geometry().height():ui->label_decode->geometry().width();
    ui->label_decode->setPixmap(pixmap.scaled(QRsize, QRsize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation));

    QImage imageToDecode = pixmap.toImage();
    QZXing decoder;
        //mandatory settings
    decoder.setDecoder( DecoderFormat_QR_CODE | DecoderFormat_EAN_13 );

    decoder.setSourceFilterType(QZXing::SourceFilter_ImageNormal);
    decoder.setTryHarderBehaviour(QZXing::TryHarderBehaviour_ThoroughScanning | QZXing::TryHarderBehaviour_Rotate);

    QString result = decoder.decodeImage(imageToDecode);
    ui->line_qrContent_2->setText(result);
}


void MainWindow::on_cBox_qrsize_stateChanged(int arg1)
{
    if(Qt::Unchecked == arg1)
    {
        ui->spin_width->setValue(640);
        ui->spin_height->setValue(640);
        ui->spin_width->setEnabled(false);
        ui->spin_height->setEnabled(false);
    }
    else if(Qt::Checked == arg1)
    {
        ui->spin_width->setEnabled(true);
        ui->spin_height->setEnabled(true);
    }
}

void MainWindow::on_btn_selqrcolor_clicked()
{
    QColor selColor = QColorDialog::getColor(Qt::white, nullptr, "", QColorDialog::ShowAlphaChannel);
    if(!selColor.isValid())
        return;
    ui->frame_qrcolor->setStyleSheet("border: 1px solid rgb(85, 85, 127);background-color:" + selColor.name(QColor::HexArgb));
}

void MainWindow::on_cBox_qrcolor_stateChanged(int arg1)
{
    if(Qt::Unchecked == arg1)
    {
        ui->frame_qrcolor->setStyleSheet("border: 1px solid rgb(85, 85, 127);background-color:#ff000000");
        ui->btn_selqrcolor->setEnabled(false);
    }
    else if(Qt::Checked == arg1)
    {
        ui->btn_selqrcolor->setEnabled(true);
    }
}


void MainWindow::on_btn_selbgcolor_clicked()
{
    QColor selColor = QColorDialog::getColor(Qt::white, nullptr, "", QColorDialog::ShowAlphaChannel);
    if(!selColor.isValid())
        return;
    ui->frame_bgcolor->setStyleSheet("border: 1px solid rgb(85, 85, 127);background-color:" + selColor.name(QColor::HexArgb));
}

void MainWindow::on_cBox_bgcolor_stateChanged(int arg1)
{
    if(Qt::Unchecked == arg1)
    {
        ui->frame_bgcolor->setStyleSheet("border: 1px solid rgb(85, 85, 127);background-color:#ffffffff");
        ui->btn_selbgcolor->setEnabled(false);
    }
    else if(Qt::Checked == arg1)
    {
        ui->btn_selbgcolor->setEnabled(true);
    }
}

void MainWindow::on_btn_savePath_clicked()
{
    QString path = QFileDialog::getExistingDirectory();
    if(path.isEmpty())
        return;
    ui->line_batchPath->setText(path);
}

